package com.Shop.Center.service;

import com.Shop.Center.dao.*;
import com.Shop.Center.entity.*;
import com.Shop.Center.util.BeanUtil;
import com.Shop.Center.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderService {

    private static final double MONEYTOCREDIT = 0.1;
    private static final double CREDITTOMONEY = 0.12;

    @Autowired
    private ItemOrderMapper itemOrderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ItemsMapper itemsMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private CreditMapper creditMapper;
    @Autowired
    private UserMapper userMapper;

    public List<ItemOrder> getAllOrders(){
        return itemOrderMapper.selectList(null);
    }


    //更新订单信息
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateOrderInfo(ItemOrder itemOrder) {//如有改动会更新整条记录
        ItemOrder temp = itemOrderMapper.selectById(itemOrder.getOrderId());
        //不为空且orderStatus>=0且状态为出库之前可以修改部分信息
        if (temp!=null&&temp.getOrderStatus()=='0') {
            temp.setTotalPrice(itemOrder.getTotalPrice());
            temp.setUserAddress(itemOrder.getUserAddress());
            return itemOrderMapper.updateById(temp);
        }
        System.out.println(temp.getOrderStatus());
        return -1;
    }

    //订单详情
    public List<OrderItem> orderDetail(Long id) {
        QueryWrapper<OrderItem> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id",id);
        return orderItemMapper.selectList(queryWrapper);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    //配货
    public List<ItemOrder> checkDone(List<Long> ids) {
        ArrayList<Long> list = new ArrayList<>();
        for (Long id : ids) {
            ItemOrder itemOrder = itemOrderMapper.selectById(id);
            if (itemOrder.getIsDeleted() == '0' && itemOrder.getOrderStatus() == '1')
                list.add(id);
        }
        List<ItemOrder> itemOrders = itemOrderMapper.selectBatchIds(list);
        for (ItemOrder itemOrder : itemOrders) {
            itemOrder.setOrderStatus('2');
            itemOrderMapper.updateById(itemOrder);
        }
        return itemOrderMapper.selectBatchIds(list);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    //出库
    public List<ItemOrder> checkOut(List<Long> ids) {
        ArrayList<Long> list = new ArrayList<>();
        for (Long id : ids) {
            ItemOrder itemOrder = itemOrderMapper.selectById(id);
            System.out.println(itemOrder.getIsDeleted()+" "+itemOrder.getOrderStatus());
            if (itemOrder.getIsDeleted() == '0' && itemOrder.getOrderStatus() == '2')
                list.add(id);
        }
        System.out.println(list.toString());
        List<ItemOrder> itemOrders = itemOrderMapper.selectBatchIds(list);
        for (ItemOrder itemOrder : itemOrders) {
            itemOrder.setOrderStatus('3');
            itemOrderMapper.updateById(itemOrder);
        }
        return itemOrderMapper.selectBatchIds(list);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public int closeOrder(List<Long> ids) {
        ArrayList<Long> list = new ArrayList<>();
        for (Long id : ids) {
            ItemOrder itemOrder = itemOrderMapper.selectById(id);
            if (itemOrder.getIsDeleted() == '1' || itemOrder.getOrderStatus() < '4')
                list.add(id);
        }
        List<ItemOrder> itemOrders = itemOrderMapper.selectBatchIds(list);
        for (ItemOrder itemOrder : itemOrders) {
            itemOrder.setOrderStatus('-');
            itemOrderMapper.updateById(itemOrder);
        }
        if(list.isEmpty()) return 0;    //说明选中的订单没有可以关闭的
        return 1;   //有成功关闭的订单
    }

    public int specifiedQuery(Date startDate, Date endDate){
        return itemOrderMapper.specifiedQuery(startDate,endDate);
    }

    @Transactional
    public List<YearStatistical> yearOrder(){
        return itemOrderMapper.yearOrder();
    }

    public List<MonthStatistical> monthOrder(){
        return itemOrderMapper.monthOrder();
    }

    @Transactional
    public String saveOrder(Long id, List<ShoppingCartItem> myShoppingCartItems) {
        User user = userMapper.selectById(id);
        List<Long> itemIdList = myShoppingCartItems.stream().map(ShoppingCartItem::getCartItemId).collect(Collectors.toList());
        List<Long> goodsIds = myShoppingCartItems.stream().map(ShoppingCartItem::getItemId).collect(Collectors.toList());
        List<Items> items = itemsMapper.selectBatchIds(goodsIds);
        Map<Long, Items> goodsMap = items.stream().collect(Collectors.toMap(Items::getId, Function.identity(), (entity1, entity2) -> entity1));
        //判断商品库存
        for (ShoppingCartItem shoppingCartItem : myShoppingCartItems) {
            //查出的商品中不存在购物车中的这条关联商品数据，直接返回错误提醒
            if (!goodsMap.containsKey(shoppingCartItem.getItemId())) {
                return "包含不存在的商品";
            }
            //存在数量大于库存的情况，直接返回错误提醒
            if (shoppingCartItem.getGoodsCount() > goodsMap.get(shoppingCartItem.getItemId()).getAmount()) {
                return "购买数量超出库存";
            }
        }
        //删除购物项
        if (!CollectionUtils.isEmpty(itemIdList) && !CollectionUtils.isEmpty(goodsIds) && !CollectionUtils.isEmpty(items)) {

                List<StockNumDTO> stockNumDTOS = BeanUtil.copyList(myShoppingCartItems, StockNumDTO.class);
            List<Items> list = itemsMapper.selectBatchIds(itemIdList);
                for(int i = 0;i<list.size();i++) {
                    Integer t = list.get(i).getAmount();
                    list.get(i).setAmount(t-myShoppingCartItems.get(i).getGoodsCount());
                    itemsMapper.updateById(list.get(i));
                }
            shoppingCartMapper.deleteBatchIds(itemIdList);
                //生成订单号
                String orderNo = NumberUtil.genOrderNo();
                Double priceTotal = 0.0;
                //保存订单
                ItemOrder itemOrder = new ItemOrder();
                itemOrder.setOrderNo(orderNo);
                itemOrder.setUserId((long) user.getId());
                itemOrder.setUserAddress(user.getAddress());
                //总价
                for (ShoppingCartItem shoppingCartItem : myShoppingCartItems) {
                    priceTotal += shoppingCartItem.getGoodsCount() * shoppingCartItem.getSellingPrice();
                }
                if(user.getPoint()*CREDITTOMONEY<=priceTotal)
                    priceTotal -= user.getPoint()*CREDITTOMONEY;
                else {
                    priceTotal = 0.0;
                    Double useCredit = priceTotal/CREDITTOMONEY;
                    user.setPoint(user.getPoint()-useCredit);
                    userMapper.updateById(user);
                }
                itemOrder.setTotalPrice(Double.parseDouble(String.format("%.2f", priceTotal)));

                //todo 订单body字段，用来作为生成支付单描述信息，暂时未接入第三方支付接口，故该字段暂时设为空字符串
                String extraInfo = "";
                itemOrder.setExtraInfo(extraInfo);
                //生成订单项并保存订单项纪录
                itemOrderMapper.insertOrder(orderNo, (long) user.getId(),priceTotal,extraInfo,user.getAddress());
                //生成所有的订单项快照，并保存至数据库
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_no",orderNo);
            itemOrder = itemOrderMapper.selectOne(queryWrapper);
                for (ShoppingCartItem shoppingCartItem : myShoppingCartItems) {
                    OrderItem orderItem = new OrderItem();
                    //使用BeanUtil工具类将newBeeMallShoppingCartItemVO中的属性复制到orderItem对象中
                    BeanUtil.copyProperties(shoppingCartItem, orderItem);
                    orderItem.setGoodsId(shoppingCartItem.getItemId());
                    //OrderMapper文件insert()方法中使用了useGeneratedKeys因此orderId可以获取到
                    orderItem.setOrderId(itemOrder.getOrderId());
                    orderItem.setSellingPrice(shoppingCartItem.getSellingPrice());
                    //保存至数据库
                    if(orderItemMapper.insertOrderItem(orderItem.getOrderId(),orderItem.getGoodsId(),
                            orderItem.getGoodsName(),orderItem.getGoodsCoverImg(),orderItem.getSellingPrice(),
                            orderItem.getGoodsCount())<0){
                        return "生成订单失败";
                    }
                    return orderNo;
                }

            return "删除商品失败";
        }
        return "购物车为空";
    }

    public ItemOrder getOrderDetailByOrderNo(String orderNo, Long userId) {
        QueryWrapper<ItemOrder> wrapper = new QueryWrapper<ItemOrder>();
        wrapper.eq("order_no",orderNo);
        ArrayList<ItemOrder> list = (ArrayList<ItemOrder>) itemOrderMapper.selectList(wrapper);
        if(list.isEmpty()) return null;
        System.out.print(list.get(0).toString());
        return list.get(0);
    }

    public List<ItemOrder> getMyOrders(Long userId) {
        QueryWrapper<ItemOrder> wrapper = new QueryWrapper<ItemOrder>();
        wrapper.eq("user_id",userId);
        return itemOrderMapper.selectList(wrapper);
    }

    public String cancelOrder(String orderNo, Long userId) {
        QueryWrapper<ItemOrder> wrapper = new QueryWrapper<ItemOrder>();
        wrapper.eq("order_no",orderNo);
        ArrayList<ItemOrder> list = (ArrayList<ItemOrder>) itemOrderMapper.selectList(wrapper);
        ItemOrder itemOrder = list.get(0);
        if (itemOrder != null) {
            //todo 验证是否是当前userId下的订单，否则报错
            //todo 订单状态判断
            if(itemOrder.getOrderStatus()=='0') { //用户可取消未支付的订单
                itemOrder.setOrderStatus('-');
                itemOrderMapper.updateById(itemOrder);
                return "取消成功";
            }
            return "订单已支付，无法取消";
        }
        return "订单不存在";
    }

    //确认收货
    public String finishOrder(String orderNo, Long userId) {
        QueryWrapper<ItemOrder> wrapper = new QueryWrapper<ItemOrder>();
        wrapper.eq("order_no",orderNo);
        ArrayList<ItemOrder> list = (ArrayList<ItemOrder>) itemOrderMapper.selectList(wrapper);
        ItemOrder itemOrder = list.get(0);
        if (itemOrder != null) {
            //todo 验证是否是当前userId下的订单，否则报错
            //todo 订单状态判断
            itemOrder.setOrderStatus('4');
            itemOrderMapper.updateById(itemOrder);
            return "订单完成";
        }
        return "订单不存在";
    }

    @Transactional
    public Double paySuccess(String orderNo, int payType, Long userId) {
        QueryWrapper<ItemOrder> wrapper = new QueryWrapper<ItemOrder>();
        wrapper.eq("order_no",orderNo);
        ArrayList<ItemOrder> list = (ArrayList<ItemOrder>) itemOrderMapper.selectList(wrapper);
        ItemOrder itemOrder = list.get(0);
        if (itemOrder != null) {
            itemOrder.setOrderStatus('1');
            itemOrder.setPayType((char) payType);
            itemOrder.setPayStatus('2');
            itemOrder.setPayTime(new Date());
            Double totalPrice = itemOrder.getTotalPrice();
            creditMapper.insertCredit(userId,itemOrder.getOrderId(),totalPrice*MONEYTOCREDIT);
            int id = Math.toIntExact(userId);
            User user = userMapper.selectById(id);
            user.setPoint(user.getPoint()+totalPrice*MONEYTOCREDIT);
            userMapper.updateById(user);
            return totalPrice*MONEYTOCREDIT;
        }
        return -1.0;
    }

    public List<OrderItem> getOrderItems(Long id) {
        ItemOrder itemOrder = itemOrderMapper.selectById(id);
        if (itemOrder != null) {
            QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",id);
            return orderItemMapper.selectList(wrapper);
        }
        return null;
    }
}
